package com.usian.controller;

import com.usian.User;
import com.usian.feign.UserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@RequestMapping("/user")
@RestController
public class UserController {

    //从Nacos注册中心获取服务端的ip、端口、要调用的服务
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    //访问Rest服务的客户端  原生的服务调用
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private UserFeign userFeign;

    //访问测试路径
    //http://localhost:8002/user/findUserById?userId=10

    @RequestMapping(value = "consumer/{userId}",method = RequestMethod.GET)
    //@RequestMapping("findUserById")
    public User findUserById(@PathVariable Integer userId){

        //找到服务提供者的服务
        ServiceInstance lbc = loadBalancerClient.choose("ribbon-provider");
        //拼接请求地址
        String url = "http://"+lbc.getHost()+":"+lbc.getPort()+"/user/findUserById/"+userId;
        //发送请求
        return restTemplate.getForObject(url,User.class);
    }

    /**
     * 占位符传参
     * @param id
     * @return
     */
    //http://localhost:8006/user/feign/13
   @RequestMapping(value = "/feign/{id}",method = RequestMethod.GET)
    public User findUserByFeign(@PathVariable Integer id){
        User user = userFeign.findUserById(id);
        return user;
    }

    /**
     * ？ 问号传参
     * @param id
     * @return
     */
    //http://127.0.0.1:8006/user/feign/findById?id=1
    @RequestMapping(value = "/feign/findById",method = RequestMethod.GET)
    //@GetMapping("/feign/findById")
    public User findById(Integer id){
        User user = userFeign.findById(id);
        return user;
    }

    /**
     * 对象传参
     * @param user
     * @return
     */

    //http://127.0.0.1:8006/user/feign/insertUser
    //{"id":11,"name":"张三","age":"11"}
    @RequestMapping(value = "/feign/insertUser",method = RequestMethod.POST)
    public String insertUser(@RequestBody User user){
        String s = userFeign.insertUser(user);
        return s;
    }


}
